<?php

class USO_language
{
	public $language_code = "en";
	public $default = "en";
	
	public $language_strings = array();
	
	public $translation_language = "en";
	
	public $id = 0;
	
	function USO_language( $language_code = false )
	{
		if ( $language_code !== false )
			$this->language_code = $language_code;
		else
			$this->language_code = $this->detect();
		
		return;
	}
	
	public function translate()
	{
		$this->translation_language = $this->default;
		
		// Have we got the language pre-defined?
		if ( isset( $this->language_strings[ $this->language_code ] ) )
		{
			if ( $this->language_strings[ $this->language_code ]["type"] == "google_translate" &&
					$this->language_strings[ $this->language_code ]["last_updated"] < ( time() - ( 24 * 60 * 60 ) ) ) {}
			else
			{
				$this->translation_language = $this->language_code;
				return $this->language_strings[ $this->language_code ]["data"];
			}
		}
		
		// Try translate it using Google translate
		if ( $translation = $this->google_translate( $this->language_code, $this->language_strings[ $this->default ]["data"], $this->default ) )
			return $translation;
		
		// Default to a known language
		if ( isset( $this->language_strings[ $this->default ] ) )
			return $this->language_strings[ $this->default ]["data"];
		
		// Shouldn't happen
		return false;
	}

	public function translate_to_xml()
	{
		$language_strings = $this->translate();
		
		$doc = new DomDocument('1.0');
		
		$translation = $doc->createElement('translation');
		$translation->setAttribute( 'lang', $this->translation_language );
		$doc->appendChild( $translation );
		
		foreach ($language_strings as $key => $value)
		{
			$string = $doc->createElement('string');
			$string->setAttribute( 'id', $key );
			
			$value = $doc->createTextNode( $value );
			$string->appendChild( $value );
			
			$translation->appendChild( $string );
		}
		
		unset( $string, $translation );
		
		return $doc;
	}
	
	public function translate_to_json()
	{
		return json_encode( $this->translate() );
	}

	private function detect()
	{
		if ( isset( $_SERVER["HTTP_ACCEPT_LANGUAGE"] ) )
		{
			preg_match( '/(.+?)(?:,|$)/', $_SERVER["HTTP_ACCEPT_LANGUAGE"], $language );
			$language = $language[1];
			
			switch ( $language_code = substr( $language, 0, 2 ) )
			{
				case 'us':
					$language = "en";
					break;
				case 'zh':
					break;
				default:
					$language = $language_code;
					break;
			}
		}
		else
			$language = $this->default;
		
		return $language;
	}
	
	public function google_translate( $destination, $string, $from = "en" )
	{
		global $sql;
		
		$url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair="
			. urlencode( $from ) . "|"
			. urlencode( $destination ) . "&";
		
		if( is_array( $string ) )
		{
			foreach ( $string as $value )
			{
				$url .= "q=" . urlencode( $value ) . "&";
			}
			$url = substr( $url, 0, -1 );
		}
		else if ( is_string( $string ) )
			$url .= "q=" . urlencode( $string );
		
		$ch = curl_init();
		curl_setopt( $ch, CURLOPT_URL, $url );
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt( $ch, CURLOPT_REFERER, "http://" . $_SERVER['SERVER_NAME'] );
		$response = curl_exec($ch);
		curl_close($ch);
		
		if ( $response !== false )
		{
			$response = $this->json_decode_safe( $response );
			
			if ( $response->responseStatus === 200 )
			{
				$array = array();
				$i = 0;
				
				if ( isset( $response->responseData->translatedText ) )
				{
					foreach ( $this->language_strings[ $this->default ]["data"] as $key => $value )
					{
						$array[ $key ] = addslashes( $this->unhtmlentities( $response->responseData->translatedText ) );
						$i++;
					}
				}
				else
				{
					foreach ( $this->language_strings[ $this->default ]["data"] as $key => $value )
					{
						$array[ $key ] = $this->unhtmlentities( $response->responseData[ $i ]->responseData->translatedText );
						$i++;
					}	
				}
				
				$this->language_strings[ $destination ] = array(
					"data"			=>	$array,
					"type"			=>	"google_translate",
					"last_updated"	=>	time()
				);
				
				$sql->update_strings( $this->id, mysql_real_escape_string( serialize( $this->language_strings ) ) );
				
				$this->translation_language = $destination;
				
				return $array;
			}
		}
		
		return false;
	}
	
	private function json_decode_safe($input)
	{
		if ( function_exists( 'json_decode' ) )
			return json_decode( $input );
	
		else
		{
			require_once 'json.php';
			$json = new Services_JSON();
			return $json->decode( $input );
		}
	
		return false;
	}
	
	private function unhtmlentities( $string )
	{
		$string = preg_replace( '~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string );
		$string = preg_replace( '~&#([0-9]+);~e', 'chr("\\1")', $string );
		
		$trans_tbl = get_html_translation_table( HTML_ENTITIES );
		$trans_tbl = array_flip( $trans_tbl );
		
		return strtr( $string, $trans_tbl );
	}
}

?>